package com.student.liu.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.student.liu.config.RabbitMQConfig;
import com.student.liu.dubbo.IDubboGoodsService;
import com.student.liu.entity.OrderformDetail;
import com.student.liu.exception.ServiceValidationException;
import com.student.liu.mapper.IOrderformDetailMapper;
import com.student.liu.service.IOrderformDetailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * 订单服务接口 实现类
 */
@Slf4j
@Service
public class OrderformDetailServiceImpl extends ServiceImpl<IOrderformDetailMapper, OrderformDetail> implements IOrderformDetailService {

    @DubboReference(
            timeout = 1000,              // 连接并读取超时时间，单位为ms，默认为1000（1s）
            mock = "com.student.liu.dubbo.mock.DubboGoodsServiceMock"    //配置模仿的降级处理效果
    )
    IDubboGoodsService dubboGoodsService;

    @Resource
    RabbitTemplate rabbitTemplate;

    @Resource
    IOrderformDetailMapper orderformDetailMapper;

    @Override
    public void createOrderformDetail(Integer goodsId,Integer orderformId, Short count) {
        //当前请求者
        Integer userId = Integer.parseInt(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        log.info("开始创建订单..");
        JSONObject goodsObject = dubboGoodsService.getGoodsById(goodsId);       //通过Dubbo获取的商品数据
        log.info("goodsObject:" + goodsObject);
        //创建订单对象
        OrderformDetail orderformDetail = new OrderformDetail();
        orderformDetail.setOrderformId(orderformId);
        orderformDetail.setGoodsId(goodsId);
        orderformDetail.setCookId(goodsObject.getInteger("cookId"));
        orderformDetail.setName(goodsObject.getString("name"));
        orderformDetail.setImage(goodsObject.getString("image"));
        orderformDetail.setNum((int) count);
        orderformDetail.setMoney(count * goodsObject.getFloat("price"));
        orderformDetail.setStateId(1);
        orderformDetail.setCreateTime(LocalDateTime.now());
        log.info("构建好的订单对象：" + orderformDetail);
        if (!save(orderformDetail)) {
            throw new ServiceValidationException("订单创建失败，请联系客服。", 402);
        }

        JSONObject jsonMessageForUserUpadteScore = new JSONObject();        //构建了一个即将发送的消息
        jsonMessageForUserUpadteScore.put("userId", userId);
        jsonMessageForUserUpadteScore.put("money", orderformDetail.getMoney());
        //向RabbitMQ发出更新用户积分的消息
        rabbitTemplate.convertAndSend(RabbitMQConfig.exchangeName, "UserUpdateScore", jsonMessageForUserUpadteScore.toString());

    }

    @Override
    public IPage<Map<String, Object>> orderDetailPage(Integer pageIndex, Integer pageSize ,Integer orderformId ) {
        Page page = new Page(pageIndex, pageSize);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.select("orderform_detail.*","cook_state.name as 'stateName'");
        queryWrapper.last("JOIN cook_state ON state_id =cook_state.id " +
                "WHERE orderform_id = " + orderformId);
        return pageMaps(page,queryWrapper);
    }

    @Override
    public IPage<Map<String, Object>> task() {
        Page page = new Page(1, 30);
        OrderformDetail orderformDetail = new OrderformDetail();
        Integer cookId = Integer.parseInt(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.select("orderform_detail.*","cook_state.name as 'stateName'");
        queryWrapper.last("JOIN cook_state ON state_id =cook_state.id " +
                "WHERE cook_id = " + cookId +
                " and state_id = " + 2);
        return pageMaps(page,queryWrapper);
    }


    @Override
    public IPage<Map<String, Object>> waiterTask() {
        Page page = new Page(1, 30);
        OrderformDetail orderformDetail = new OrderformDetail();
        Integer cookId = Integer.parseInt(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.select("orderform_detail.*","cook_state.name as 'stateName'");
        queryWrapper.last("JOIN cook_state ON state_id =cook_state.id " +
                " where state_id = " + 3);
        return pageMaps(page,queryWrapper);
    }

    /**
     * 修改订单状态
     * @param
     * @param state
     */
    @Override
    public void update(Integer orderformId,Byte state) {
        OrderformDetail orderformDetail = new OrderformDetail();
        orderformDetail.setStateId((int) state);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("orderform_id",orderformId);
        update(orderformDetail,queryWrapper);
    }


    /**
     * 修改订单状态
     * @param
     * @param state
     */
    @Override
    public void waiterupdate(Integer id,Byte state) {
        OrderformDetail orderformDetail = new OrderformDetail();
        orderformDetail.setStateId((int) state);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id",id);
        update(orderformDetail,queryWrapper);
    }

    /**
     * 修改订单状态
     * @param
     * @param state
     */
    @Override
    public void cookUpdateState(Integer id,Byte state) {
        OrderformDetail orderformDetail = new OrderformDetail();
        orderformDetail.setStateId((int) state);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id",id);
        update(orderformDetail,queryWrapper);
    }


    @Override
    public void remove(Integer id) {
        removeById(id);
    }

}
